/* components */
import QualificationForm from '@src/modules/setting/messageChannel/components/qualification/dialog/form'
import QualificationBaseDialog from '@src/modules/setting/messageChannel/components/qualification/dialog/base'
/* hooks */
import { useDialog } from '@hooks/useDialog'
/* vue */
import { defineComponent, PropType } from 'vue'
/* model */
import { 
  BusinessLicenseTypeCNNEnum,
  BusinessLicenseTypeEnum,
  DocumentTypeCNNEnum,
  DocumentTypeEnum,
  SMSQualificationFormStepEnum
} from '@src/modules/setting/messageChannel/components/qualification/model/enum'
import { 
  SMSQualificationCompanyFields, 
  SMSQualificationPersonFields, 
  SMSQualificationOtherFields 
} from '@src/modules/setting/messageChannel/components/qualification/model/fields'
/* scss */
import '@src/modules/setting/messageChannel/components/qualification/dialog/view.scss'
import MsgModel from '@model/MsgModel'
import { getQualificationData } from '@src/api/MessageApi'
import { message } from '@src/util/message'
import * as FormUtil from '@src/component/form/util'
import { cloneDeep, isFalsy } from 'pub-bbx-utils'
import Field from '@model/entity/Field'
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
import { convertQualificationAttachment } from '@src/modules/setting/messageChannel/components/qualification/util'

export default defineComponent({
  name: 'QualificationFormView',
  props: {
    
  },
  setup(props, { emit }) {
    
    const { visible: insideVisible, showDialog, hideDialog } = useDialog()
    
    return {
      visible: insideVisible,
      showDialog,
      hideDialog,
    }
    
  },
  data() {
    return {
      companyForm: {},
      personForm: {},
      otherForm: {},
      loading: false
    }
  },
  computed: {
    title(): string {
      return '资质认证'
    },
    confirmButtonText(): string {  
      return this.$t('common.base.close') as string
    },
    attrs(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ]
      }
    },
    allFields(): Field[] {
      return [
        ...SMSQualificationCompanyFields as Field[],
        ...SMSQualificationPersonFields as Field[],
        ...SMSQualificationOtherFields as Field[]
      ]
    },
    imageDisplayFields() {
      // 图片字段
      // @ts-ignore
      return this.allFields.filter((field: Field) => {
        const formTypes = [
          FieldTypeMappingEnum.ImageDisplay,
          FieldTypeMappingEnum.Attachment
        ]
        return formTypes.includes(field.formType as FieldTypeMappingEnum)
      })
    },
    imageDisplayFieldNameMap(): Record<string, Field> {
      // @ts-ignore
      return this.imageDisplayFields.reduce((acc: Record<string, Field>, field: Field) => {
        acc[field.fieldName] = field
        return acc
      }, {})
    }
  },
  methods: {
    async getQualificationData() {
      try {
        
        this.loading = true
        
        const result = await getQualificationData()
        const isFail = MsgModel.isFail(result)
        if (isFail) {
          message.error(result.message)
          return
        }
        
        const data = MsgModel.getData(result, {}) as Record<string, any> 
        this.initForm(data)
        
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    initForm(value: Record<string, any>) {
      
      const newValue = cloneDeep(value || {})
      
      // 营业证件类型字段处理
      const businessLicenseType = newValue.businessLicenseType as unknown as BusinessLicenseTypeEnum
      const newBusinessLicenseType = BusinessLicenseTypeCNNEnum[businessLicenseType]
      newValue.businessLicenseType = newBusinessLicenseType

      // 证件类型字段处理
      const documentType = newValue.documentType as unknown as DocumentTypeEnum
      const newDocumentType = DocumentTypeCNNEnum[documentType]
      newValue.documentType = newDocumentType
      
      const personLiableDocumentType = newValue.personLiableDocumentType as unknown as DocumentTypeEnum
      const newPersonLiableDocumentType = DocumentTypeCNNEnum[personLiableDocumentType]
      newValue.personLiableDocumentType = newPersonLiableDocumentType
      
      // 图片字段处理
      const imageDisplayFieldNameMap = this.imageDisplayFieldNameMap
      for (const fieldName in imageDisplayFieldNameMap) {
        
        const field = imageDisplayFieldNameMap[fieldName]
        // @ts-ignore
        const fieldValue = newValue[fieldName]
        
        if (isFalsy(value)) {
          continue
        }
        
        const limit = Number(field?.setting?.limit)
        const isMulti = limit > 1
        
        if (isFalsy(isMulti)) {
          const newFieldValue = convertQualificationAttachment(fieldValue)
          newValue[fieldName] = [newFieldValue]
        }
        
      }
      
      let companyForm: Record<string, any> = {}
      for (const field of SMSQualificationCompanyFields) {
        const fieldName = field.fieldName
        companyForm[fieldName] = newValue[fieldName]
      }
      
      let personForm: Record<string, any> = {}
      for (const field of SMSQualificationPersonFields) {
        const fieldName = field.fieldName
        personForm[fieldName] = newValue[fieldName]
      }
      
      let otherForm: Record<string, any> = {}
      for (const field of SMSQualificationOtherFields) {
        const fieldName = field.fieldName
        otherForm[fieldName] = newValue[fieldName]
      }
      
      let newCompanyForm = FormUtil.initialize(SMSQualificationCompanyFields, {
        attribute: companyForm
      })
      let newPersonForm = FormUtil.initialize(SMSQualificationPersonFields, {
        attribute: personForm
      })
      let newOtherForm = FormUtil.initialize(SMSQualificationOtherFields, {
        attribute: otherForm
      })
      
      this.companyForm = newCompanyForm
      this.personForm = newPersonForm
      this.otherForm = newOtherForm
      
    },
    openDialog() {
      this.getQualificationData()
      this.showDialog()
    },
    onClose() {
      this.hideDialog()
    },
    async onConfirm() {
      this.hideDialog()
    },
    renderFormView() {
      return (
        <div class="qualification-form-view">
          {this.renderStepCompany()}
          {this.renderStepPerson()}
          {this.renderStepOther()}
        </div>
      )
    },
    renderStepCompany() {
      return (
        <div class="qualification-form-company">
          <div class="qualification-form-title">
            1. 企业信息
          </div>
          <form-view
            ref="CompanyForm"
            value={this.companyForm}
            fields={SMSQualificationCompanyFields}
          >
          </form-view>
        </div>
      )
    },
    renderStepPerson() {
      return (
        <div class="qualification-form-person">
          <div class="qualification-form-title">
            2. 责任人信息
          </div>
          <form-view
            ref="PersonForm"
            value={this.personForm}
            fields={SMSQualificationPersonFields}
          >
          </form-view>
        </div>
      )
    },
    renderStepOther() {
      return (
        <div class="qualification-form-other">
          <div class="qualification-form-title">
            3. 其他材料
          </div>
          <form-view
            ref="OtherForm"
            value={this.otherForm}
            fields={SMSQualificationOtherFields}
          >
          </form-view>
        </div>
      )
    }
  },
  render() {
    return (
      <QualificationBaseDialog
        {...this.attrs}
        visible={this.visible}
        title={this.title}
        onClose={this.onClose}
        onConfirm={this.onConfirm}
        confirmText={this.confirmButtonText}
      >
        {this.renderFormView()}
      </QualificationBaseDialog>
    )
  }
})